from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render

from django.views import View
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_jwt.utils import jwt_encode_handler,jwt_decode_handler
from utils.smscode import send_sms_code
from .models import User, Cz
import json
import re
import random
import redis
import hashlib

"""发送短信验证码"""
class SmsCode(APIView):
    def get(self,request):
        mobile = request.query_params.get("mobile")
        if not re.match(r'^1[3-9][0-9]{9}$', mobile):
            return Response({'code': 400, 'msg': 'mobile格式有误!'})
        data = random.randint(10000,99999)
        resp = send_sms_code(mobile,data)
        r = redis.Redis()
        r.setex("sms_%s"%mobile,500,data)
        return Response({"code":0,"msg":"发送成功"})

"""注册"""
class Register(APIView):
    def post(self,request):
        mobile = request.data.get("mobile")
        smscode = request.data.get("smscode")
        password = request.data.get("password")

        if not all([mobile,smscode,password]):
            return Response({"code":400,"msg":"参数不完整"})

        r = redis.Redis()
        code = r.get("sms_%s"%mobile)

        if not code :
            return Response({"code":400,"msg":"验证码过期请重新发送验证码"})

        if code.decode() != smscode:
            return Response({"code":400,"msg":"验证码错误"})

        user = User.objects.filter(mobile=mobile).first()
        if user:
            return Response({"code":400,"msg":"用户已存在"})

        md5 = hashlib.md5()
        md5.update(password.encode())
        md5_pwd = md5.hexdigest()

        username = "ss_%s"%mobile
        try:
            a = User.objects.create(
                mobile=mobile,
                username=username,
                blance=0,
                password=md5_pwd)
        except Exception as e:
            print("注册失败的原因>>>>",e)
            return Response({"code":400,"msg":"注册失败"})

        return Response({"code":0,"msg":"注册成功"})


"""手机验证码登录接口"""
class CodeLogin(APIView):
    def post(self,request):
        mobile = request.data.get("mobile")
        smscode = request.data.get("smscode")
        if not re.match(r'^1[3-9][0-9]{9}$', mobile):
            return Response({'code': 400, 'msg': 'mobile格式有误!'})

        user = User.objects.filter(mobile=mobile).first()
        if not user:
            return Response({"code":400,"msg":"没有该用户 请先注册"})

        r = redis.Redis()
        code = r.get("sms_%s"%mobile)
        if not code :
            return Response({"code":400,"msg":"验证码过期请重新发送验证码"})

        if code.decode() != smscode:
            return Response({"code":400,"msg":"验证码错误"})


        payload = {
            "user_id":user.id,
            "username":user.username
        }
        token = jwt_encode_handler(payload)

        return Response({"code":0,"msg":"登录成功","token":token})


"""账号密码登录"""
class Login(APIView):
    def post(self,request):
        name = request.data.get("username")
        password = request.data.get("password")

        if not all([name,password]):
            return Response({"code":400,"msg":"请输入帐号密码"})

        user = User.objects.filter(Q(username=name) | Q(mobile=name)).first()
        if not user:
            return Response({"code":400,"msg":"请先注册"})

        md5 = hashlib.md5()
        md5.update(password.encode())
        md5_pwd = md5.hexdigest()

        if user.password != md5_pwd:
            return Response({"code":400,"msg":"账号或密码错误"})

        payload = {
            "user_id":user.id,
            "username":user.username
        }
        token = jwt_encode_handler(payload)

        return Response({"code":0,"msg":"登录成功","token":token})


"""获取用户信息"""
class GetUser(APIView):
    def get(self,request):
        token = request.headers.get("token")

        if not token:
            return Response({"code":400,"msg":"没有token"})

        user_data = jwt_decode_handler(token)

        user_id = user_data["user_id"]

        user = User.objects.filter(id=user_id).first()
        if not user:
            return Response({"code":400,"msg":"没有该用户"})

        user_data = {
            "id":user.id,
            "username":user.username,
            "mobile":user.mobile,
            "qm":user.qm
        }
        return Response({"code":0,"msg":"获取成功","data":user_data})


"""上传头像"""
class Upload(APIView):
    def put(self,request):
        token = request.headers.get("token")
        img = request.FILES.get("img")

        if not token:
            return Response({"code":400,"msg":"没有token"})
        user_data = jwt_decode_handler(token)

        user_id = user_data["user_id"]

        user = User.objects.filter(id=user_id).first()
        if not user:
            return Response({"code":400,"msg":"没有该用户"})
        return Response(img.name)


"""修改手机号"""
class UpMobile(APIView):
    def put(self,request):
        mobile = request.data.get("mobile")
        token = request.headers.get("token")
        smscode = request.data.get("smscode") # 原本用的手机号验证码

        if not token:
            return Response({"code": 400, "msg": "没有token"})
        user_data = jwt_decode_handler(token)

        user_id = user_data["user_id"]

        user = User.objects.filter(id=user_id).first()

        r = redis.Redis()
        code = r.get("sms_%s" % user.mobile)
        if not code:
            return Response({"code": 400, "msg": "验证码过期请重新发送验证码"})

        if code.decode() != smscode:
            return Response({"code": 400, "msg": "验证码错误"})


        try:
            user = User.objects.filter(id=user_id).update(mobile=mobile)
            return Response({"code":0,"msg":"修改成功"})
        except Exception as e:
            return Response({"code":400,"msg":"修改失败"})


"""修改个人资料"""
class Update(APIView):
    def put(self, request):
        token = request.headers.get("token")
        username = request.data.get("username")
        qm = request.data.get("qm")

        if not token:
            return Response({"code": 400, "msg": "没有token"})

        user_data = jwt_decode_handler(token)

        user_id = user_data["user_id"]

        user = User.objects.filter(id=user_id).first()
        if not user:
            return Response({"code": 400, "msg": "没有该用户"})

        try:
            user = User.objects.filter(id=user_id).update(
                username=username,
                qm=qm,
            )
            return Response({"code": 0, "msg": "修改成功"})
        except Exception as e:
            print("修改失败的》》》》", e)
            return Response({"code": 400, "msg": "修改失败"})




"""获取充值"""
class GetCz(APIView):
    def get(self,request):
        token = request.headers.get("token")
        if not token:
            return Response({"code": 400, "msg": "请先登录"})

        user_data = jwt_decode_handler(token)

        user_id = user_data["user_id"]

        user = User.objects.filter(id=user_id).first()
        if not user:
            return Response({"code": 400, "msg": "没有该用户"})


        cz =  Cz.objects.all()

        list = []
        for i in cz:
            data = {
                "id":i.id,
                "dd":i.dd,
                "price":i.price
            }

            list.append(data)

        return Response({"code":0,"msg":"获取成功","data":list})





